<template>
	<cl-page>
		<view class="promotion-list">
			<!-- 活动分类 -->
			<view class="category-tabs">
				<scroll-view class="tabs-scroll" scroll-x>
					<view class="tabs-list">
						<view
							class="tab-item"
							v-for="category in categories"
							:key="category.value"
							:class="{ active: activeCategory === category.value }"
							@tap="switchCategory(category.value)"
						>
							<cl-icon
								:name="category.icon"
								size="20"
								:color="activeCategory === category.value ? '#667eea' : '#666'"
							></cl-icon>
							<text class="tab-text">{{ category.label }}</text>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 活动列表 -->
			<view class="content">
				<cl-scroller
					:ref="setRefs('scroller')"
					@down="refresh"
					@up="loadmore"
					:down="{ stopPropagation: true }"
					:up="{ stopPropagation: true }"
				>
					<view class="promotion-items">
						<view v-for="item in list" :key="item.billNo">
							<!-- 秒杀 -->
							<seckill-card
								v-if="item.promType === '秒杀'"
								:promotion="item"
								@join="joinPromotion"
							/>

							<!-- 套餐 -->
							<combo-card
								v-else-if="item.promType === '套餐'"
								:promotion="item"
								@join="joinPromotion"
							/>

							<!-- 买赠 -->
							<buygift-card
								v-else-if="item.promType === '买赠'"
								:promotion="item"
								@join="joinPromotion"
							/>
						</view>
					</view>
					<cl-empty
						v-if="list.length === 0 && !loading"
						:fixed="false"
						:height="400"
						text="暂无促销活动"
						icon="gift"
					/>
				</cl-scroller>
			</view>
		</view>
	</cl-page>
</template>

<script lang="ts" setup>
import { ref, watch, nextTick } from "vue";
import { onLoad as onPageLoad, onShow } from "@dcloudio/uni-app";
import { useCool } from "/@/cool";
import { useUi } from "/$/cool-ui";
import SeckillCard from "./components/seckill-card.vue";
import ComboCard from "./components/combo-card.vue";
import BuygiftCard from "./components/buygift-card.vue";
import dayjs from "dayjs";

const { service, router, refs, setRefs } = useCool();
const ui = useUi();

const activeCategory = ref("MS");
const list = ref<any[]>([]);
const loading = ref(false);
const finished = ref(false);

const categories = [
	{ label: "秒杀", value: "MS", icon: "zap" },
	{ label: "套餐", value: "TC", icon: "package" },
	{ label: "买赠", value: "MZ", icon: "gift" },
];

// 页面参数
onPageLoad((query?: Record<string, any> | undefined) => {
	if (query?.type) {
		switch (query.type) {
			case "seckill":
				activeCategory.value = "MS";
				break;
			case "combo":
				activeCategory.value = "TC";
				break;
			case "buyGift":
				activeCategory.value = "MZ";
				break;
		}
	}
});

onShow(() => {
	// 延迟加载确保组件已渲染
	setTimeout(() => {
		loadData();
	}, 100);
});

// 促销类型与接口映射
const promotionApiMap: Record<string, Function> = {
	MS: () => service.goods.promo.getComboDetailsByType({ promType: "MS" }),
	TC: () => service.goods.promo.getComboDetailsByType({ promType: "TC" }),
	MZ: () => service.goods.promo.getComboDetailsByType({ promType: "MZ" }),
};

// 加载数据
async function loadData() {
	if (loading.value) return;

	loading.value = true;
	ui.showLoading();

	try {
		let resultList: any[] = [];

		const apiCall = promotionApiMap[activeCategory.value];
		if (apiCall) {
			const res = await apiCall();
			resultList = res || [];
		}

		// 统一处理状态、时间、折扣等
		const processedList = resultList.map((item: any) => ({
			...item,
			statusText: getStatusText(item),
			remainingTime: calculateRemainingTime(item.startTime, item.endTime),
			discountText: formatDiscountText(item),
		}));

		// 过滤掉不在时间范围内的活动
		const now = Date.now();
		const filteredList = processedList.filter((item: any) => {
			const start = dayjs(item.startTime).valueOf();
			const end = dayjs(item.endTime).valueOf();
			// 只显示已开始且未结束的活动
			return now >= start && now <= end && item.status === 1;
		});

		// 按开始时间倒序
		filteredList.sort((a, b) => dayjs(b.startTime).valueOf() - dayjs(a.startTime).valueOf());
		console.log("filteredList", filteredList);
		// 打印买赠数据结构
		const buyGiftItems = filteredList.filter(item => item.promType === '买赠');
		if (buyGiftItems.length > 0) {
			console.log("买赠活动数据:", buyGiftItems[0]);
			if (buyGiftItems[0].details && buyGiftItems[0].details.length > 0) {
				console.log("买赠详情:", buyGiftItems[0].details[0]);
			}
		}
		list.value = filteredList;
		finished.value = true;
	} catch (error) {
		console.error("加载促销活动失败:", error);
		ui.showToast("加载失败，请重试");
	} finally {
		loading.value = false;
		ui.hideLoading();
		// 结束下拉刷新
		if (refs.scroller) {
			refs.scroller.end();
		}
	}
}

// 下拉刷新
async function refresh() {
	list.value = [];
	finished.value = false;
	await loadData();
}

// 上拉加载更多（这里暂时不需要分页）
function loadmore() {
	if (refs.scroller) {
		refs.scroller.end();
	}
}

// 切换分类
function switchCategory(value: string) {
	if (activeCategory.value === value) return;

	activeCategory.value = value;
	list.value = [];
	finished.value = false;

	nextTick(() => {
		loadData();
	});
}

// 监听分类变化
watch(activeCategory, () => {
	// 分类变化时已在switchCategory中处理
});

function getStatusText(item: any): string {
	const now = Date.now();
	const start = dayjs(item.startTime).valueOf();
	const end = dayjs(item.endTime).valueOf();
	if (item.status === 0) return "已停用";
	if (now < start) return "未开始";
	if (now > end) return "已结束";
	return "进行中";
}

function calculateRemainingTime(startTime: string, endTime: string): string {
	const now = Date.now();
	const start = dayjs(startTime).valueOf();
	const end = dayjs(endTime).valueOf();
	if (now < start) return "未开始";
	if (now > end) return "已结束";
	const diff = end - now;
	const days = Math.floor(diff / (1000 * 60 * 60 * 24));
	const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
	const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
	if (days > 0) return `${days}天${hours}小时`;
	if (hours > 0) return `${hours}小时${minutes}分钟`;
	return `${minutes}分钟`;
}

function formatDiscountText(item: any): string {
	switch (item.promType) {
		case "MS":
			const detail = item.details?.[0];
			if (detail) {
				const discount = (
					(Number(detail.seckillPrice) / Number(detail.goodsInfo.price)) *
					10
				).toFixed(1);
				return `${discount}折`;
			}
			return "特惠价";
		case "TC":
			return "套餐优惠";
		case "MZ":
			return "买赠活动";
		default:
			return "特惠活动";
	}
}

// 参与促销活动（由子组件处理具体逻辑）
function joinPromotion(promotion: any) {
	// 刷新列表
	setTimeout(() => {
		loadData();
	}, 1500);
}
</script>

<style lang="scss" scoped>
.promotion-list {
	padding: 20rpx;

	.category-tabs {
		background-color: #fff;
		border-radius: 24rpx;
		padding: 20rpx 0;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

		.tabs-scroll {
			white-space: nowrap;
			padding: 0 20rpx;
		}

		.tabs-list {
			display: inline-flex;
			align-items: center;

			.tab-item {
				display: flex;
				align-items: center;
				padding: 12rpx 24rpx;
				margin-right: 16rpx;
				border-radius: 32rpx;
				background-color: #f5f5f5;
				transition: all 0.3s;

				&:last-child {
					margin-right: 0;
				}

				.tab-text {
					margin-left: 8rpx;
					font-size: 26rpx;
					color: #666;
				}

				&.active {
					background-color: #667eea;

					.tab-text {
						color: #fff;
					}
				}
			}
		}
	}

	.content {
		height: calc(100vh - 200rpx);

		.promotion-items {
			padding: 0 4rpx;

			> view {
				margin-bottom: 24rpx;

				&:last-child {
					margin-bottom: 0;
				}
			}
		}
	}
}
</style>
